package dp.gr03.payroll.payrollApplication;

import java.util.HashMap;
import java.util.Scanner;

import dp.gr03.payroll.application.InputParser;
import dp.gr03.payroll.application.commands.AddEmployeeCommand;
import dp.gr03.payroll.application.commands.ChangeEmployeeCommand;
import dp.gr03.payroll.application.commands.DeleteEmployeeCommand;
import dp.gr03.payroll.application.commands.PayDayCommand;
import dp.gr03.payroll.application.commands.SalesReceiptCommand;
import dp.gr03.payroll.application.commands.ServiceChargeCommand;
import dp.gr03.payroll.application.commands.TimeCardCommand;
import dp.gr03.payroll.application.commands.TransactionParser;
import dp.gr03.payroll.exception.PayRollException;

public class Payroll
{

    private HashMap<String, TransactionParser> parsers;

    //use_cli is used with unit testing
    public Payroll(boolean use_cli)
    {
        loadTransActionParsers();

        InputParser inputParser = new InputParser();
        Scanner sc = new Scanner(System.in);

        String line = null;
        if(use_cli){
        System.out.println("Welkom bij het Payrollsysteem, voer je commando in");
            while ((line = sc.nextLine()) != null)
            {
                String[] arguments = inputParser.parse(line);
                processCommand(arguments);
            }
        }
    }

    public void processCommand(String[] arguments)
    {
        if (arguments.length > 0)
        {
            TransactionParser p = getParserForCommand(arguments[0]);
            if (p != null)
            {
                Transaction t;
                try
                {
                    t = p.parse(arguments);
                    t.execute();

                } catch (PayRollException e)
                {
                    System.out.println(e.getMessage());
                }
            } else
            {
                System.out.println("The command '"+arguments[0]+"' doesn't exist.");
            }
        }
    }

    private TransactionParser getParserForCommand(String command)
    {
        return parsers.get(command);
    }

    private void loadTransActionParsers()
    {
        parsers = new HashMap<String, TransactionParser>();
        registerParser(new AddEmployeeCommand());
        registerParser(new ChangeEmployeeCommand());
        registerParser(new DeleteEmployeeCommand());
        registerParser(new TimeCardCommand());
        registerParser(new SalesReceiptCommand());
        registerParser(new ServiceChargeCommand());
        registerParser(new PayDayCommand());
    }

    private void registerParser(TransactionParser tp)
    {
        parsers.put(tp.getActionString(), tp);
    }

    /**
     * @param args
     * @throws PayRollException
     */
    public static void main(String[] args) throws PayRollException
    {
        new Payroll(true);
    }

}
